import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_hotwork/utils/color_helper.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart' show DateFormat;

class VoicePlayerView extends StatefulWidget {
  final String path; // 音频路径
  final FlutterSound flutterSound; // 语音播放器
  final Function onClose;
  final String duration;
  final String title;
  final height;
  final color;
  var isStartPlayer;

  VoicePlayerView(this.path, this.flutterSound,
      {this.onClose,
      this.title,
      this.height = 80.0,
      this.color,
      this.duration = '00:00',
        this.isStartPlayer,
      Key key})
      : super(key: key);

  @override
  _VoicePlayerViewState createState() => _VoicePlayerViewState();
}

class _VoicePlayerViewState extends State<VoicePlayerView> {
  var _isClosebtn = false; //  控制关闭按钮是否显示
  var _visibleView = true; //  控制整个视图组件是否显示

  // 音频播放
  StreamSubscription _playerSubscription;
  double sliderCurrentPosition = 0.0;
  double maxDuration = 1.0;
  bool _isPaused = false;
  // bool _isStartPlayer = true; // 是否开启播放

  String _duration;

  @override
  void initState() {
    super.initState();
    if (widget.onClose != null) {
      _isClosebtn = true;
    }
    _duration = widget.duration;
    widget.flutterSound.setSubscriptionDuration(0.01);
    widget.flutterSound.setDbPeakLevelUpdate(0.8);
    widget.flutterSound.setDbLevelEnabled(true);
    initializeDateFormatting();
  }

  // 关闭页面组件
  _closeView() {
    // 删除这个音频文件
    File file = File(widget.path);
    file?.delete();
    // ignore: deprecated_member_use
    if (widget.flutterSound.isPlaying) {
      stopPlayer();
    }
    widget.onClose();
    setState(() {
      _visibleView = false;
    });
  }

  // 开始播放
  void _startPlayer() async {
    try {
      String path = await widget.flutterSound.startPlayer(widget.path);
      await widget.flutterSound.setVolume(1.0);
      print('startPlayer: $path');
      _playerSubscription =
          widget.flutterSound.onPlayerStateChanged.listen((e) {
        if (e != null) {
          maxDuration = e.duration;
          sliderCurrentPosition = e.currentPosition;
          this.setState(() {
            _duration = _durationTime(e.currentPosition);
          });

          if (e.currentPosition == e.duration) {
            print('播放结束');
            this.setState(() {
              sliderCurrentPosition = 0.0;
              _duration = widget.duration;
              widget.isStartPlayer = true;
            });
          }
        }
      });
    } catch (err) {
      print('error: $err');
    }
  }

  // 停止播放
  void stopPlayer() async {
    try {
      String result = await widget.flutterSound.stopPlayer();
      print('stopPlayer: $result');
      if (_playerSubscription != null) {
        _playerSubscription.cancel();
        _playerSubscription = null;
      }
    } catch (err) {
      print('error: $err');
    }
  }

  // 暂停播放
  void _pausePlayer() async {
    String result = await widget.flutterSound.pausePlayer();
    print('pausePlayer: $result');
  }

  // 恢复播放
  void _resumePlayer() async {
    String result = await widget.flutterSound.resumePlayer();
    print('resumePlayer: $result');
  }

  // 拖动播放
  void seekToPlayer(int milliSecs) async {
    String result = await widget.flutterSound.seekToPlayer(milliSecs);
    print('seekToPlayer: $result');
  }

  _playOrPauseVoice() {
    if (widget.isStartPlayer == true) {
      // 是否开启播放
      // Fluttertoast.showToast(msg: '开始播放');
      print("======开始播放");
      widget.isStartPlayer = false;
      _startPlayer();
    } else {
      // 暂停与恢复播放
      if (_isPaused == true) {
        // Fluttertoast.showToast(msg: '恢复播放');
        print("======恢复播放");
        _isPaused = false;
        _resumePlayer();
      } else {
        // Fluttertoast.showToast(msg: '暂停');
        print("======暂停");
        _isPaused = true;
        _pausePlayer();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Visibility(
      visible: _visibleView,
      child: Container(
        height: widget.height,
        decoration: BoxDecoration(
            color: widget.color ?? Color.fromRGBO(255, 255, 255, 1),
            borderRadius: BorderRadius.all(Radius.circular(10)),
            border: Border.all(color: ColorHelper.hexColor('#EBEBEB'))),
        child: Stack(
          overflow: Overflow.visible,
          children: <Widget>[
            Row(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SizedBox(
                  width: 20,
                ),
                GestureDetector(
                  onTap: _playOrPauseVoice,
                  child: Icon(
                    Icons.last_page,
                    color: ColorHelper.mainBlueColor,
                    size: 30,
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        '    ${widget.title ?? '录音音频'}',
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(height: 10),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: <Widget>[
                          Expanded(
                            child: Container(
                                height: 10.0,
                                child: SliderTheme(
                                  data: SliderTheme.of(context).copyWith(
                                    activeTrackColor: ColorHelper.mainBlueColor,
                                    //进度条滑块左边颜色
                                    inactiveTrackColor: Colors.grey[300],
                                    //进度条滑块右边颜色
                                    thumbColor: ColorHelper.mainBlueColor,
                                    thumbShape: RoundSliderThumbShape(
                                      //可继承SliderComponentShape自定义形状
                                      disabledThumbRadius: 7, //禁用是滑块大小
                                      enabledThumbRadius: 7, //滑块大小
                                    ),
                                  ),
                                  child: Slider(
                                      value: sliderCurrentPosition,
                                      min: 0.0,
                                      max: maxDuration,
                                      divisions: maxDuration.toInt(),
                                      onChanged: (double value) async {
                                        print('onChanged');
                                        this.setState(() {
                                          _duration = _durationTime(value);
                                          sliderCurrentPosition = value;
                                        });
                                      },
                                      onChangeStart: (double value) async {
                                        print('Start');
                                        // ignore: deprecated_member_use
                                        if (widget.flutterSound.isPlaying ==
                                            false) {
                                          widget.isStartPlayer = false;
                                          _startPlayer();
                                          print('Start');
                                        } else {
                                          print('Start_resumePlayer');
                                          // _resumePlayer();
                                          await widget.flutterSound
                                              .seekToPlayer(value.toInt());
                                        }
                                      },
                                      onChangeEnd: (double value) async {
                                        print('End');
                                        setState(() {
                                          sliderCurrentPosition = value;
                                        });
                                        // ignore: deprecated_member_use
                                        if (widget.flutterSound.isPlaying) {
                                          print('seekToPlayer');
                                          await widget.flutterSound
                                              .seekToPlayer(value.toInt());
                                        } else {
                                          print('_resumePlayer');
                                          _resumePlayer();
                                          await widget.flutterSound
                                              .seekToPlayer(value.toInt());
                                        }
                                      }),
                                )),
                          ),
                          Text('$_duration',
                              style:
                                  TextStyle(color: Colors.black, fontSize: 13)),
                          SizedBox(
                            width: 10,
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ],
            ),
            Positioned(
                top: -7,
                right: -7,
                child: GestureDetector(
                  onTap: _closeView,
                  child: Visibility(
                    visible: _isClosebtn,
                    child: Icon(
                      Icons.delete,
                      color: Colors.red,
                      size: 20,
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }

  _durationTime(double time) {
    DateTime date =
        new DateTime.fromMillisecondsSinceEpoch(time.toInt(), isUtc: true);
    String txt = DateFormat('mm:ss:SS', 'en_GB').format(date);
    return txt.substring(0, 5);
  }
}
